﻿namespace Devonline.Core;

/// <summary>
/// IFormatProvider and ICustomFormatter implement extensions
/// </summary>
public static class FormatterExtensions
{
    /// <summary>
    /// value to format string for IFormatProvider and ICustomFormatter implement
    /// </summary>
    /// <typeparam name="T">the type which is implemented from IFormatProvider and ICustomFormatter</typeparam>
    /// <param name="value">origin value</param>
    /// <param name="format">format string</param>
    /// <returns>value formatted string</returns>
    public static string ToString<T>(this decimal value, string format = AppSettings.DEFAULT_FORMAT_STRING) where T : IFormatProvider, ICustomFormatter, new()
    {
        return string.Format(new T(), format, value);
    }

    /// <summary>
    /// 人民币金额转大写
    /// </summary>
    /// <param name="value">人民币金额</param>
    /// <returns></returns>
    public static string ToUpperMoney(this decimal value) => string.Format(new MoneyFormatter(), AppSettings.DEFAULT_FORMAT_STRING, value);

    /// <summary>
    /// 小数四舍五入保留后 默认保留 2 位小数点的格式化显示
    /// </summary>
    /// <param name="value">原始值</param>
    /// <param name="length">保留的小数位长度</param>
    /// <returns></returns>
    public static string Default(this decimal value, int length = AppSettings.UNIT_TWO) => Math.Round(value, length).ToString();
    /// <summary>
    /// 小数四舍五入后固定保留 2 位小数点的格式化显示
    /// </summary>
    /// <param name="value">原始值</param>
    /// <returns></returns>
    public static string Default(this decimal value) => value.Default(AppSettings.UNIT_TWO);
    /// <summary>
    /// 小数转换为百分比显示, 默认显示 2 位小数位
    /// </summary>
    /// <param name="value">原始值</param>
    /// <param name="length">保留的小数位长度</param>
    /// <returns></returns>
    public static string Percentage(this decimal value, int length = AppSettings.UNIT_TWO) => Math.Round(value * AppSettings.UNIT_HUNDRED, length).ToString() + AppSettings.CHAR_QUESTION;
    /// <summary>
    /// 小数转换为百分比显示, 固定显示 2 位小数位
    /// </summary>
    /// <param name="value">原始值</param>
    /// <returns></returns>
    public static string Percentage(this decimal value) => value.Percentage(AppSettings.UNIT_TWO);
}